import { getToken, setToken, removeToken, getUserInfo, setUserInfo, removeUserInfo } from '@/utils/auth'

const getDefaultState = () => {
  const userInfo = getUserInfo()
  return {
    token: getToken(),
    name: userInfo?.name || '',
    avatar: userInfo?.avatar || '',
    roles: userInfo?.roles || [],
    merchantId: userInfo?.merchantId || null
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_MERCHANT_ID: (state, id) => {
    state.merchantId = id
  }
}

const actions = {
  // 登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      // 模拟登录接口
      setTimeout(() => {
        if (username === 'admin' && password === '123456') {
          // 管理员登录
          const token = 'admin-token'
          const userInfo = {
            name: '系统管理员',
            avatar: '',
            roles: ['admin'],
            merchantId: null
          }
          commit('SET_TOKEN', token)
          setToken(token)
          setUserInfo(userInfo)
          commit('RESET_STATE')
          resolve()
        } else if (username === 'merchant' && password === '123456') {
          // 商户登录
          const token = 'merchant-token'
          const userInfo = {
            name: '测试商户',
            avatar: '',
            roles: ['merchant'],
            merchantId: 1
          }
          commit('SET_TOKEN', token)
          setToken(token)
          setUserInfo(userInfo)
          commit('RESET_STATE')
          resolve()
        } else {
          reject(new Error('用户名或密码错误'))
        }
      }, 1000)
    })
  },

  // 获取用户信息
  getInfo({ commit }) {
    return new Promise((resolve) => {
      const userInfo = getUserInfo()
      if (userInfo) {
        commit('RESET_STATE')
        resolve(userInfo)
      } else {
        resolve(null)
      }
    })
  },

  // 登出
  logout({ commit }) {
    return new Promise((resolve) => {
      removeToken()
      removeUserInfo()
      commit('RESET_STATE')
      resolve()
    })
  },

  // 重置token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      removeUserInfo()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 